/**
 * 编辑邮件模板页面
 */
import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Space,
  message,
  Row,
  Col,
  Switch,
  Divider,
  Tag,
  Tabs,
  Spin,
} from 'antd';
import { ArrowLeftOutlined, EyeOutlined, ApiOutlined, DatabaseOutlined, SaveOutlined } from '@ant-design/icons';
import { history, useParams } from '@umijs/max';
import EnhancedEmailEditor from '@/components/EnhancedEmailEditor';
import SystemVariablePanel from '@/components/SystemVariablePanel';
import {
  getEmailTemplate,
  updateEmailTemplate,
  extractTemplateVariables,
  previewTemplate,
  type EmailTemplateUpdate,
  type TemplateVariableExtractRequest,
  type TemplatePreviewRequest,
  TemplateType,
  TemplateCategory,
} from '@/services/emailTemplate';
import { getDataSources, type DataSourceItem } from '@/services/dataSource';

const { Option } = Select;
const { TextArea } = Input;
const { TabPane } = Tabs;

const EditEmailTemplate: React.FC = () => {
  const params = useParams();
  const templateId = parseInt(params.id as string);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [pageLoading, setPageLoading] = useState(true);
  const [extractLoading, setExtractLoading] = useState(false);
  const [previewLoading, setPreviewLoading] = useState(false);
  const [extractedVariables, setExtractedVariables] = useState<string[]>([]);
  const [previewData, setPreviewData] = useState<any>(null);
  const [activeTab, setActiveTab] = useState('edit');
  const [dataSources, setDataSources] = useState<DataSourceItem[]>([]);
  const [selectedDataSource, setSelectedDataSource] = useState<number | undefined>();
  const [emailContent, setEmailContent] = useState({ subject: '', content: '' });

  // 获取数据源列表
  const fetchDataSources = async () => {
    try {
      const response = await getDataSources({ page: 1, size: 100 });
      setDataSources(response.items);
    } catch (error) {
      console.error('获取数据源失败:', error);
    }
  };

  // 获取邮件模板详情
  const fetchEmailTemplate = async () => {
    try {
      const template = await getEmailTemplate(templateId);
      form.setFieldsValue({
        name: template.name,
        template_type: template.template_type,
        category: template.category,
        description: template.description,
        is_active: template.is_active,
      });
      setEmailContent({
        subject: template.subject,
        content: template.content,
      });
      setExtractedVariables(template.variables || []);
    } catch (error: any) {
      message.error(error.message || '获取模板详情失败');
      history.push('/templates');
    } finally {
      setPageLoading(false);
    }
  };

  useEffect(() => {
    if (templateId) {
      fetchEmailTemplate();
      fetchDataSources();
    }
  }, [templateId]);

  // 处理表单提交
  const handleSubmit = async (values: EmailTemplateUpdate) => {
    setLoading(true);
    try {
      await updateEmailTemplate(templateId, {
        ...values,
        subject: emailContent.subject,
        content: emailContent.content,
        variables: extractedVariables,
      });
      message.success('邮件模板更新成功');
      history.push('/templates');
    } catch (error: any) {
      message.error(error.message || '更新失败');
    } finally {
      setLoading(false);
    }
  };

  // 提取模板变量
  const handleExtractVariables = async () => {
    try {
      const values = await form.validateFields(['content', 'subject']);
      setExtractLoading(true);

      const extractData: TemplateVariableExtractRequest = {
        content: values.content,
        subject: values.subject,
      };

      const result = await extractTemplateVariables(extractData);
      setExtractedVariables(result.variables);
      message.success(`提取到 ${result.variables.length} 个变量`);
    } catch (error: any) {
      if (error.errorFields) {
        message.warning('请先填写模板内容和主题');
      } else {
        message.error(error.message || '变量提取失败');
      }
    } finally {
      setExtractLoading(false);
    }
  };

  // 预览模板
  const handlePreview = async () => {
    try {
      const values = await form.validateFields(['subject', 'content', 'template_type']);
      setPreviewLoading(true);

      const previewRequest: TemplatePreviewRequest = {
        subject: values.subject,
        content: values.content,
        template_type: values.template_type,
        variables: {}, // 可以添加示例变量值
      };

      const result = await previewTemplate(previewRequest);
      setPreviewData(result);
      setActiveTab('preview');
      message.success('预览生成成功');
    } catch (error: any) {
      if (error.errorFields) {
        message.warning('请先填写必要的模板信息');
      } else {
        message.error(error.message || '预览生成失败');
      }
    } finally {
      setPreviewLoading(false);
    }
  };

  if (pageLoading) {
    return (
      <PageContainer>
        <Card>
          <div style={{ textAlign: 'center', padding: '50px 0' }}>
            <Spin size="large" />
          </div>
        </Card>
      </PageContainer>
    );
  }

  return (
    <PageContainer
      header={{
        title: '编辑邮件模板',
        breadcrumb: {},
      }}
      extra={[
        <Button
          key="back"
          icon={<ArrowLeftOutlined />}
          onClick={() => history.push('/templates')}
        >
          返回列表
        </Button>,
      ]}
    >
      <Card>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="编辑模板" key="edit">
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSubmit}
            >
              <Row gutter={24}>
                <Col span={12}>
                  <Form.Item
                    name="name"
                    label="模板名称"
                    rules={[
                      { required: true, message: '请输入模板名称' },
                      { min: 2, message: '模板名称至少需要2个字符' },
                    ]}
                  >
                    <Input placeholder="请输入模板名称" />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item name="description" label="模板描述">
                    <Input placeholder="请输入模板描述（可选）" />
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={24}>
                <Col span={8}>
                  <Form.Item
                    name="category"
                    label="模板分类"
                    rules={[{ required: true, message: '请选择模板分类' }]}
                  >
                    <Select placeholder="请选择模板分类">
                      <Option value={TemplateCategory.MARKETING}>营销邮件</Option>
                      <Option value={TemplateCategory.NOTIFICATION}>通知邮件</Option>
                      <Option value={TemplateCategory.NEWSLETTER}>新闻邮件</Option>
                      <Option value={TemplateCategory.WELCOME}>欢迎邮件</Option>
                      <Option value={TemplateCategory.REMINDER}>提醒邮件</Option>
                      <Option value={TemplateCategory.CUSTOM}>自定义</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    name="template_type"
                    label="模板类型"
                    rules={[{ required: true, message: '请选择模板类型' }]}
                  >
                    <Select placeholder="请选择模板类型">
                      <Option value={TemplateType.HTML}>HTML</Option>
                      <Option value={TemplateType.MARKDOWN}>Markdown</Option>
                      <Option value={TemplateType.PLAIN_TEXT}>纯文本</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label="关联数据源">
                    <Select
                      placeholder="选择数据源（可选）"
                      allowClear
                      value={selectedDataSource}
                      onChange={setSelectedDataSource}
                    >
                      {dataSources.map(ds => (
                        <Option key={ds.id} value={ds.id}>
                          <Space>
                            <DatabaseOutlined />
                            {ds.name}
                          </Space>
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>
              </Row>

              {/* 增强的邮件编辑器 */}
              <div style={{ marginBottom: 24 }}>
                <EnhancedEmailEditor
                  value={emailContent}
                  onChange={setEmailContent}
                  dataSourceId={selectedDataSource}
                  templateType={form.getFieldValue('template_type') || TemplateType.HTML}
                  onPreview={(previewResult) => {
                    setPreviewData(previewResult);
                    setActiveTab('preview');
                  }}
                />
              </div>

              {/* 变量提取结果 */}
              {extractedVariables.length > 0 && (
                <div style={{ marginBottom: 16 }}>
                  <Divider orientation="left">提取的变量</Divider>
                  <Space wrap>
                    {extractedVariables.map((variable, index) => (
                      <Tag key={index} color="blue">
                        {variable}
                      </Tag>
                    ))}
                  </Space>
                </div>
              )}

              <Row gutter={24}>
                <Col span={12}>
                  <Form.Item name="is_active" label="启用状态" valuePropName="checked">
                    <Switch checkedChildren="启用" unCheckedChildren="禁用" />
                  </Form.Item>
                </Col>
              </Row>

              <Form.Item>
                <Space>
                  <Button
                    type="default"
                    icon={<ApiOutlined />}
                    onClick={handleExtractVariables}
                    loading={extractLoading}
                  >
                    提取变量
                  </Button>
                  <Button
                    type="default"
                    icon={<EyeOutlined />}
                    onClick={handlePreview}
                    loading={previewLoading}
                  >
                    预览模板
                  </Button>
                  <Button type="primary" htmlType="submit" loading={loading}>
                    更新模板
                  </Button>
                  <Button onClick={() => history.push('/templates')}>
                    取消
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </TabPane>

          <TabPane tab="预览效果" key="preview">
            {previewData ? (
              <div>
                <Card title="预览结果" style={{ marginBottom: 16 }}>
                  <div style={{ marginBottom: 16 }}>
                    <strong>渲染后的主题：</strong>
                    <div style={{ marginTop: 8, padding: 8, backgroundColor: '#f5f5f5' }}>
                      {previewData.rendered_subject}
                    </div>
                  </div>
                  
                  <div style={{ marginBottom: 16 }}>
                    <strong>HTML内容：</strong>
                    <div 
                      style={{ 
                        marginTop: 8, 
                        padding: 16, 
                        border: '1px solid #d9d9d9',
                        backgroundColor: '#fff',
                        minHeight: 200,
                      }}
                      dangerouslySetInnerHTML={{ __html: previewData.html_content }}
                    />
                  </div>

                  {previewData.variables_used.length > 0 && (
                    <div style={{ marginBottom: 16 }}>
                      <strong>使用的变量：</strong>
                      <div style={{ marginTop: 8 }}>
                        <Space wrap>
                          {previewData.variables_used.map((variable: string, index: number) => (
                            <Tag key={index} color="green">
                              {variable}
                            </Tag>
                          ))}
                        </Space>
                      </div>
                    </div>
                  )}

                  {previewData.missing_variables.length > 0 && (
                    <div>
                      <strong>缺失的变量：</strong>
                      <div style={{ marginTop: 8 }}>
                        <Space wrap>
                          {previewData.missing_variables.map((variable: string, index: number) => (
                            <Tag key={index} color="red">
                              {variable}
                            </Tag>
                          ))}
                        </Space>
                      </div>
                    </div>
                  )}
                </Card>
              </div>
            ) : (
              <div style={{ textAlign: 'center', padding: 50, color: '#999' }}>
                请先在编辑页面点击"预览模板"按钮生成预览
              </div>
            )}
          </TabPane>
        </Tabs>
      </Card>
    </PageContainer>
  );
};

export default EditEmailTemplate;
